﻿--[[
   @brief    update_guide_control
   @author   neilzxhuang
   @version  1.0
   @date     2015-04-14
--]]

update_guide_constant = {
    UPDATE_GUIDE_DISPALY = "UPDATE_GUIDE_DISPALY";
    UPDATE_GUIDE_CLOSE   = "UPDATE_GUIDE_CLOSE";
    UPDATE_GUIDE_MORE    = "UPDATE_GUIDE_MORE";
    UPDATE_GUIDE_OPEN    = 113;
};
update_guide_tips_control =
{
    game_id_list = {};
    ctrl2item = {};
    game_select = 0;
    list_ptr = nil;
    -- 我的游戏列表
    update_game_list = nil;
    -- 游戏列表对应的人数
    update_game_peoplenum_list = nil;

    peoplenum_serverulr = LoadStr("PEOPLENUM_SERVER_URL");

    init = function()
        base_utility.log("update_guide_control.init called");
        ierd_tgp.tpf_ui.Require("auto_update_guide\\view.lua");
        ierd_tgp.tpf_ui.Require("auto_update_guide\\item.lua");
    end;

    open_update_guide_dialog = function(event_id, json_str)

        -- 判断是否曾经打开过
        local b_opened = update_guide_tips_control.get_autoupdate_status();
        if b_opened then
            return;
        end;

        -- 判断是否全部开启了自动更新
        local b_show = update_guide_tips_control.get_autoupdate_gamelist();
        if not b_show then
            return;
        end;

        if update_guide_tips_view.update_guide_exist == false then
            update_guide_tips_view.update_guide_exist = true;
            layout_mgr.restore_layout("auto_update_tips.tpf"); 
        end

        -- 发送"显示自动更新"的QOS
        tqos_mgr.remember_btn_clicked(update_guide_constant.UPDATE_GUIDE_DISPALY);

        -- 向后台请求开启用户数
        update_guide_tips_control.request_openpeople_num();

        update_guide_tips_control.show_game_list();
        update_guide_tips_view.show_dialog(TRUE);
        event_center.send_event(suggest_predownload_event.CLOSE, "");
        -- 将打开状态置为1
        update_guide_tips_control.set_autoupdate_status(1);
    end;

    -- 返回是否点击过自动更新
    get_autoupdate_status = function()
        local b_hasbeen_opened = false;
        local path = "update_tips.autoupdate.openedupdatedlg.opened";
        local path_len = string.len(path);
        -- 读取是否打开过“立即更新”
        local gl_adapter =
            base_utility.get_component_adapter("IGame_library",
                "ierd_tgp.game_library.Get_game_library_adapter();");
        if nil ~= gl_adapter then
            local val_opened = 0;
            local ret_opened = nil;
            ret_opened, val_opened = gl_adapter:GetCfgInfoByPathInt(path,
                                                    path_len, val_opened);
            if false == ret_opened then
                -- 读取配置失败，写一次配置,返回没有点击过
                update_guide_tips_control.set_autoupdate_status(0);
                b_hasbeen_opened = false;
            else
                -- 读取成功
                if tonumber(val_opened) == 1 then
                    -- 打开过自动更新
                    b_hasbeen_opened = true;
                else
                    -- 没有打开过
                    b_hasbeen_opened = false;
                end;
            end;
            return b_hasbeen_opened;
        end;
    end;

    -- 设置是否点击过自动更新
    set_autoupdate_status = function(dw_opened)
        local path = "update_tips.autoupdate.openedupdatedlg.opened";
        local path_len = string.len(path);
        -- 读取是否打开过“立即更新”
        local gl_adapter =
            base_utility.get_component_adapter("IGame_library",
                "ierd_tgp.game_library.Get_game_library_adapter();");
        if nil ~= gl_adapter then
            local val_opened = 0;
            local ret_opened = nil;

            ret_opened = gl_adapter:SetCfgInfoByPathInt(path,
                                                    path_len, dw_opened);
            if nil == ret_opened or false == ret_opened then
                -- 写配置失败，写一次配置,返回没有点击过
                base_utility.log("[set_autoupdate_status] write opened data failed");
            end;
        end;
    end;

    -- 获取所有需要更新的游戏列表：返回：false:没有;true:有
    get_autoupdate_gamelist = function()
        local game_list = banner_model.visible_game_list;
        local count = game_list.count;
        update_guide_tips_control.update_game_list = {};
        if game_list == nil or count == nil then 
            base_utility.log("show_game_list.init called get game_base_info failed");
            return false;
        end;

        local installed_game_list = ierd_tgp.game_library.Game_list:new_local();
        local gl_adapter =
            base_utility.get_component_adapter("IGame_library",
                "ierd_tgp.game_library.Get_game_library_adapter();");
        if gl_adapter ~= nil then
            gl_adapter:get_installed_games(installed_game_list);
        end;

        for i = 0, count-1 do
            local game_id = game_list.game_id_list[i];
            local is_installed = update_guide_tips_control.is_game_installed(
                                                    game_id,
                                                    installed_game_list);
            if game_id ~= nil then
                local game_base_info = banner_model.get_game_base_info(game_id);
                if game_base_info ~= nil and game_base_info.type ~= nil and 
                    game_base_info.type ~= ierd_tgp.game_library.GAME_LIST_TYPE_WEB and
                    game_base_info.type ~= ierd_tgp.game_library.GAME_LIST_TYPE_PHONE and
                    is_installed == true then
                    table.insert(update_guide_tips_control.update_game_list, game_id);
                end
            end
        end

        -- 过滤掉已经开启自动更新的游戏
        update_guide_tips_control.filter_game_list();

        -- 进行排序
        update_guide_tips_control.sort_game_list();

        -- 全部都设置过了，则不弹出
        if update_guide_tips_control.update_game_list == nil or table.getn(update_guide_tips_control.update_game_list) == 0 then
            return false;
        else
            return true;
        end;
        return true;
    end;

    -- 判断游戏是否已经安装到本地
    is_game_installed = function(game_id, installed_game_list)
        local length = installed_game_list.count;
        local is_install = false;
        for i = 0, length - 1 do
            if installed_game_list.game_id_list[i] == game_id then
                is_install = true;
                break;
            end;
        end;
        return is_install;
    end;

    -- 显示游戏列表：返回：false:不显示更新框;true:显示更新框
    show_game_list = function()

        base_utility.log("show_game_list.init called");
        update_guide_tips_control.list_ptr = ui_utility.get_ctrl_ptr_by_cid(CID_AUTO_UPDATE_GAME_LIST);
        if update_guide_tips_control.list_ptr == nil then 
            base_utility.log("show_game_list.init called get game_base_info failed");
            return false;
        end

        -- 设置显示数量
        local dw_item_count = #(update_guide_tips_control.update_game_list);
        -- 设置有多少款游戏可以开启
        update_guide_tips_view.set_update_game_num(dw_item_count);

        if dw_item_count > 3 then
            dw_item_count = 3;
        end;
        update_guide_tips_control.list_ptr:SetItemCount(dw_item_count);

        -- 显示游戏列表
        for i = 1, dw_item_count do
            local game_id = update_guide_tips_control.update_game_list[i];
            if game_id ~= nil then
                local game_base_info = banner_model.get_game_base_info(game_id);
                local item_id = update_guide_tips_control.list_ptr:GetItemRootIDByIdx(i-1);
                update_guide_tips_control.list_ptr:SetItemDraggable(i-1,false);
                if item_id ~= 0 and game_base_info ~= nil then
                    local item = Item:new(game_id, item_id);
                    update_guide_tips_view.show_item_info(game_base_info, item_id);
                    update_guide_tips_control.game_id_list[game_id] = item_id;
                    update_guide_tips_control.ctrl2item[item_id] = item;
                end
            end
        end;
        update_guide_tips_control.game_select = 0;
    end;

    -- 对游戏列表进行排序,保持和工具箱中的排序规则一样
    sort_game_list = function()
        local temp_game_state_list = banner_model.game_state_list;
        local count = temp_game_state_list.count;

        local need_update_list = {};
        local pre_download_list = {};
        local pre_download_list_ex = {};
        local normal_list = {};

        for i = 1, table.getn(update_guide_tips_control.update_game_list) do
            for j = 1, count do
                if update_guide_tips_control.update_game_list[i] == temp_game_state_list.game_state[j - 1].iGame_id then
                    if temp_game_state_list.game_state[j - 1].iState == 4 or
                       temp_game_state_list.game_state[j - 1].iState == 5 or
                       temp_game_state_list.game_state[j - 1].iState == 6 then
                       --游戏需要更新、正在更新和游戏更新失败的列表
                        table.insert(need_update_list, update_guide_tips_control.update_game_list[i]);
                    elseif temp_game_state_list.game_state[j - 1].iPre_download == 1 then
                        local game_lib =
                            base_utility.get_component_adapter("IGame_library",
                                "ierd_tgp.game_library.Get_game_library_adapter();");
                        local state_info = ierd_tgp.game_library.Pre_Update_Status_Info:new();
                            if game_lib ~= nil then
                                game_lib:get_preupdate_status_info(temp_game_state_list.game_state[j - 1].iGame_id, 
                                state_info);
                            end;
                        if state_info.formal_update_after_ > 0 then 
                            table.insert(pre_download_list, update_guide_tips_control.update_game_list[i]);
                        else
                            table.insert(normal_list, update_guide_tips_control.update_game_list[i]);
                        end;
                        state_info:delete();
                    else
                        table.insert(normal_list, update_guide_tips_control.update_game_list[i]);
                    end;
                end;
            end;
        end;
        update_guide_tips_control.update_game_list = {};
        for i = 1, table.getn(need_update_list) do
            table.insert(update_guide_tips_control.update_game_list, need_update_list[i]);
        end;
        for i = 1, table.getn(pre_download_list) do
            table.insert(update_guide_tips_control.update_game_list, pre_download_list[i]);
        end;
        for i = 1, table.getn(normal_list) do
            table.insert(update_guide_tips_control.update_game_list, normal_list[i]);
        end;
    end;

    -- 对游戏列表进行过滤
    filter_game_list = function()
        local temp_game_state_list = banner_model.game_state_list;
        local count = temp_game_state_list.count;
        local temp_update_game_list = {};
        for i = 1, table.getn(update_guide_tips_control.update_game_list) do
            for j = 1, count do
                if update_guide_tips_control.update_game_list[i] == temp_game_state_list.game_state[j - 1].iGame_id then
                    -- 条件：没有开启自动更新，且有自动更新功能
                    if temp_game_state_list.game_state[j - 1].iAuto_update ~= 1 and 
                            temp_game_state_list.game_state[j - 1].iSupport_update ~= 0
                                    then
                        -- 该游戏没有自动更新
                        table.insert(temp_update_game_list, update_guide_tips_control.update_game_list[i]);
                    end;
                end;
            end;
        end;

        -- 赋值回update_list
        update_guide_tips_control.update_game_list = {};
        for i = 1, table.getn(temp_update_game_list) do
            table.insert(update_guide_tips_control.update_game_list, temp_update_game_list[i]);
        end;
    end;

    -- 发送开启用户数请求
    request_openpeople_num = function()
        base_utility.curl_request_async (update_guide_tips_control.peoplenum_serverulr,
            "update_guide_tips_control.on_get_openpeople_num", true);
    end;

    -- 请求开启用户数回调函数
    on_get_openpeople_num = function(s_json)
        if nil ~= s_json and string.len(s_json) > 0 then
            -- 过滤json串
            local tb_peoplenum = {};
            local b_success, tb_peoplenum = update_guide_tips_control.srv_string_to_table(s_json, "all_game_update");
            if not b_success then
                base_utility.log("[on_get_openpeople_num]failed to parse json,return");
                return;
            end;
            update_guide_tips_control.update_game_peoplenum_list = {};

            local dw_updategame_num = table.getn(update_guide_tips_control.update_game_list);
            for key, value in pairs(tb_peoplenum) do
                local dw_gameid = tonumber(key);
                for i = 1, dw_updategame_num do
                    -- 找到一个gameid
                    if update_guide_tips_control.update_game_list[i] == dw_gameid then
                        local game_peoplenum = {};
                        game_peoplenum["gameid"] = dw_gameid;
                        game_peoplenum["peoplenum"] = tonumber(value["auto"]);
                        table.insert(update_guide_tips_control.update_game_peoplenum_list, game_peoplenum);
                    end;
                end; 
            end;

            -- 更新显示
            local dw_item_count = #(update_guide_tips_control.update_game_list);
            for i = 1, dw_item_count do
                local dw_game_id = update_guide_tips_control.update_game_list[i];
                local dw_item_id = update_guide_tips_control.game_id_list[dw_game_id];
                local dwopenpeople_num = update_guide_tips_control.lookfor_openpeople_num(dw_game_id);
                -- 更新界面
                update_guide_tips_view.set_openuser_num(dwopenpeople_num, dw_item_id);
            end;
        end;
    end;

    -- 将从后台获取的返回值解析成table值
    -- srv_rsp: server返回的数据，可以为空
    -- var_name: 返回的js变量名字段，用于校验
    -- return: 
    --     1.bool 是否成功获取到有效的结果,第一个返回值为false时后面返回值都为nil
    --     2.table 由js变量具体json字符串转换成的table
    srv_string_to_table = function(srv_rsp, var_name)
        if nil == srv_rsp then
            return false;
        end;

        if nil == var_name then
            return false;
        end;

        local prefix = "var "..var_name.." = ";
        local tail = ";";
        local outer_len = string.len(prefix .. tail);
        local rsp_len = string.len(srv_rsp);
        if rsp_len < outer_len then
            return false;
        end;

        local prefix_start, prefix_end = string.find(srv_rsp, prefix, 1, true);
        if prefix_start == 1 then
            local tail_reg = "%" .. tail .. "[^%" .. tail .. "]*$";
            local tail_start, tail_end = string.find(srv_rsp, tail_reg);
            if tail_end == rsp_len then
                -- 说明格式正确
                local real_rsp = string.sub(srv_rsp, prefix_end + 1, tail_start - 1);
                local real_table = base_utility.json_to_table(real_rsp);
                if real_table ~= nil then
                    return true, real_table;
                end;
            end;
        end;
        return false;
    end;

    -- 根据gameid查找开启人数
    lookfor_openpeople_num = function(dw_gameid)
        local dw_openpeople_num = 0;
        if nil ~= update_guide_tips_control.update_game_peoplenum_list
            and table.getn(update_guide_tips_control.update_game_peoplenum_list) > 0 then
            local dw_list_num = table.getn(update_guide_tips_control.update_game_peoplenum_list);
            for i = 1, dw_list_num do
                local game_peoplenum = update_guide_tips_control.update_game_peoplenum_list[i];
                if dw_gameid == game_peoplenum["gameid"] then
                    dw_openpeople_num = game_peoplenum["peoplenum"];
                    break;
                end;
            end;
        end;
        -- 按照公式计算假数据
        -- math.randomseed(tostring(os.time()):reverse():sub(1,6));
        -- local dw_rand_num = math.random(200, 300);
        -- local dw_return_num = 13527 + dw_openpeople_num * dw_rand_num / 100;
        -- 服务端没有取到数据，赋初始值
        if dw_openpeople_num == 0 then
            dw_openpeople_num = 13527;
        end;
        return dw_openpeople_num;
    end;

    clear_all_data_info = function()
        for id, val in pairs(update_guide_tips_control.game_id_list) do
            update_guide_tips_control.game_id_list[id] = nil;
        end
    end;

    is_game_auto_update = function()
        local game_state = ierd_tgp.game_library.GameState:new();
        local game_lib =
            base_utility.get_component_adapter("IGame_library",
                "ierd_tgp.game_library.Get_game_library_adapter();");
        local game_list = banner_model.visible_game_list;
        local count = game_list.count;
        for i = 0, count-1 do
            local game_id = game_list.game_id_list[i];
            game_lib:get_game_state(game_id, game_state);
            if game_state.iAuto_update ~= 0 then
                game_state:delete();
                return true;
            end
        end
        game_state:delete();
        return false;
    end;

    click_game_update_count = function()
      local game_lib =
          base_utility.get_component_adapter("IGame_library",
              "ierd_tgp.game_library.Get_game_library_adapter();");
      local click_count = game_lib:get_click_update_btn_count();
      game_lib:set_click_update_btn_count(click_count+1);
      return click_count;
    end;

    get_main_wnd_rect = function()
      local component = ui_utility.get_ctrl_ptr_by_cid(CID_MAINFRAME_Dialog_MainFrame);
        if component ~= NULL then
            update_guide_tips_view.main_wnd_rect = component:GetRectEx(TRUE,TRUE);
        end
    end;
    select_item = function(uilib, dwID_Click)
        update_guide_tips_control.game_select = update_guide_tips_control.game_select + 1;
        if update_guide_tips_control.game_select == 1 then
            local component = ui_utility.get_ctrl_ptr_by_cid(CID_AUTO_UPDATE_OK_BTN);
            component:Enable(TRUE);
        end
    end;
    unselect_item = function(uilib, dwID_Click)
        update_guide_tips_control.game_select = update_guide_tips_control.game_select - 1;
        if update_guide_tips_control.game_select == 0 then
            local component = ui_utility.get_ctrl_ptr_by_cid(CID_AUTO_UPDATE_OK_BTN);
            component:Enable(FALSE);
        end
    end;

};

update_guide_tips_control.init();